package cn.juc;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 银行取钱问题 CAS
 */
@Slf4j
public class BankTest {
    public static void main(String[] args) {
        Account account=new CasSafe(10000);
        demo(account);
    }

    static class CasSafe implements Account{
        private AtomicInteger balance;
        CasSafe(int balance){
            this.balance=new AtomicInteger(balance);
        }
        @Override
        public Integer getBalance() {
            return balance.get();
        }

        @Override
        public void withDraw(Integer amount) {
            //最新余额
            int pre=balance.get();
            log.info("最新余额:"+pre);
            //要修改的余额
            int next=pre-amount;
            log.info("修改:"+next);
            while (true){
                if (balance.compareAndSet(pre,next)){
                    break;
                }
            }
        }
    }
    interface Account{
        Integer getBalance();
        void withDraw(Integer amount);
    }
    static void demo(Account account){
        List<Thread> threadList=new ArrayList<>();
        for (int i = 0; i <1 ; i++) {
            threadList.add(new Thread(()->{account.withDraw(10);}));
        }
        threadList.forEach(Thread::start);
        threadList.forEach(t-> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        System.out.println("还有多少钱："+account.getBalance());
    }
}
